<template>
  <div>
    <el-dialog title="题目设置" :visible.sync="visible">
      <div class="form-container">
        <el-form
          :model="tableForm"
          ref="tableForm"
          :rules="tableRules"
          class="form-item"
        >
          <el-form-item label="题目" prop="question">
            <el-input
              :disabled="disabled"
              v-model="tableForm.question"
              placeholder="请输入题目"
            ></el-input>
          </el-form-item>

          <el-form-item label="选项A" prop="item1">
            <el-input
              v-model="tableForm.item1"
              placeholder="请输入选项A"
              :disabled="disabled"
            ></el-input>
          </el-form-item>
          <el-form-item label="选项B" prop="item2">
            <el-input
              v-model="tableForm.item2"
              placeholder="请输入选项B"
              :disabled="disabled"
            ></el-input>
          </el-form-item>
          <el-form-item label="选项C" prop="item3">
            <el-input
              v-model="tableForm.item3"
              placeholder="请输入选项C"
              :disabled="disabled"
            ></el-input>
          </el-form-item>
          <el-form-item label="选项D" prop="item4">
            <el-input
              v-model="tableForm.item4"
              placeholder="请输入选项D"
              :disabled="disabled"
            ></el-input>
          </el-form-item>
          <el-form-item label="答案" prop="answer">
            <el-select
              multiple
              v-model="tableForm.answer"
              placeholder="请选择答案"
              :disabled="disabled"
            >
              <el-option
                v-for="(item, index) in answer"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="答案解析" prop="remark">
            <el-input
              type="textarea"
              autosize
              v-model="tableForm.remark"
              :disabled="disabled"
              placeholder="答案解析"
            ></el-input>
          </el-form-item>
          <el-form-item label="课程" prop="subjectId">
            <el-cascader
              v-model="selectedSubjectPath"
              :options="subjectTree"
              :props="{ checkStrictly: true, emitPath: true }"
              :disabled="disabled"
              placeholder="请选择课程"
              filterable
              clearable
              @change="handleSubjectChange"
            ></el-cascader>
          </el-form-item>
          <el-form-item
            v-if="showSpecialList"
            label="特别关注点"
            prop="specialCareId"
          >
            <el-select
              filterable
              :disabled="disabled"
              v-model="tableForm.specialCareId"
              placeholder="请选择特别关注点"
            >
              <el-option
                v-for="item in specialCaresList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <!-- 英文版表单 -->
        <el-form
          v-if="showQuestionTranslated"
          :model="questionTranslated"
          :rules="questionTranslatedRules"
          ref="questionTranslated"
          class="form-item"
        >
          <el-form-item label="Question" prop="question">
            <el-input
              :disabled="disabled"
              v-model="questionTranslated.question"
              placeholder="Please enter the question"
            ></el-input>
          </el-form-item>
          <!-- 英文版没有课程选项 -->
          <el-form-item label="Item A" prop="item1">
            <el-input
              v-model="questionTranslated.item1"
              placeholder="Please enter item A"
              :disabled="disabled"
            ></el-input>
          </el-form-item>
          <el-form-item label="Item B" prop="item2">
            <el-input
              v-model="questionTranslated.item2"
              placeholder="Please enter item B"
              :disabled="disabled"
            ></el-input>
          </el-form-item>
          <el-form-item label="Item C" prop="item3">
            <el-input
              v-model="questionTranslated.item3"
              placeholder="Please enter item C"
              :disabled="disabled"
            ></el-input>
          </el-form-item>
          <el-form-item label="Item D" prop="item4">
            <el-input
              v-model="questionTranslated.item4"
              placeholder="Please enter item D"
              :disabled="disabled"
            ></el-input>
          </el-form-item>
          <el-form-item label="Answer" prop="answer">
            <el-select
              multiple
              v-model="questionTranslated.answer"
              placeholder="Please select the answer"
              :disabled="disabled"
            >
              <el-option
                v-for="(item, index) in answer"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="Explanation" prop="remark">
            <el-input
              type="textarea"
              autosize
              v-model="questionTranslated.remark"
              :disabled="disabled"
              placeholder="Explanation"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="getQuestionTranslated" v-if="disabled"
          >查看双语版</el-button
        >
        <el-button
          type="primary"
          v-if="editFlag && !disabled"
          @click="checkQuestionTranslated"
          >编辑双语版</el-button
        >
        <el-button
          v-show="!disabled"
          @click="resetHandler('tableForm')"
          icon="el-icon-refresh"
          >重置</el-button
        >
        <el-button
          v-show="!disabled"
          type="primary"
          @click="submit('tableForm')"
          icon="el-icon-check"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json 文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import questionApi from "@/api/question/index";
import subjectApi from "@/api/subject/index";
import specialCareApi from "@/api/specialCare/index";
import questionTranslatedApi from "@/api/questionTranslated";
import questionTranslated from "@/api/questionTranslated";
export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    const validateQuestion = (rule, value, callback) => {
      if (!value) {
        callback(new Error("问题不得为空！"));
      } else {
        let trim = value.trim();
        if (trim == "") {
          callback(new Error("问题不得为空！"));
        } else {
          callback();
        }
      }
    };
    const validateSubject = (rule, value, callback) => {
      if (!value) {
        callback(new Error("所在模块不得为空！"));
      } else if (value == "") {
        callback(new Error("所在模块不得为空！"));
      } else {
        callback();
      }
    };
    const validateChapter = (rule, value, callback) => {
      if (!value) {
        callback(new Error("所在章节不得为空！"));
      } else {
        callback();
      }
    };
    const validateItem1 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("选项1不得为空！"));
      } else {
        callback();
      }
    };
    const validateItem2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("选项2不得为空！"));
      } else {
        callback();
      }
    };
    const validateItem3 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("选项3不得为空！"));
      } else {
        callback();
      }
    };
    const validateItem4 = (rule, value, callback) => {
      callback();
    };
    const validateAnswer = (rule, value, callback) => {
      if (value.length > 0) {
        callback();
      } else {
        callback(new Error("答案不得为空！"));
      }
    };
    // 验证是否包含中文字符
    const validateChinese = (rule, value, callback) => {
      if (value && /[\u4e00-\u9fa5]/.test(value)) {
        callback(new Error("英文版不能包含中文字符！"));
      } else {
        callback();
      }
    };
    // 英文版验证函数
    const validateEnglishQuestion = (rule, value, callback) => {
      if (!value) {
        callback(new Error("Question cannot be empty!"));
      } else {
        let trim = value.trim();
        if (trim == "") {
          callback(new Error("Question cannot be empty!"));
        } else if (/[\u4e00-\u9fa5]/.test(value)) {
          callback(
            new Error("English version cannot contain Chinese characters!")
          );
        } else {
          callback();
        }
      }
    };
    const validateEnglishItem1 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("Item A cannot be empty!"));
      } else if (/[\u4e00-\u9fa5]/.test(value)) {
        callback(
          new Error("English version cannot contain Chinese characters!")
        );
      } else {
        callback();
      }
    };
    const validateEnglishItem2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("Item B cannot be empty!"));
      } else if (/[\u4e00-\u9fa5]/.test(value)) {
        callback(
          new Error("English version cannot contain Chinese characters!")
        );
      } else {
        callback();
      }
    };
    const validateEnglishItem3 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("Item C cannot be empty!"));
      } else if (/[\u4e00-\u9fa5]/.test(value)) {
        callback(
          new Error("English version cannot contain Chinese characters!")
        );
      } else {
        callback();
      }
    };
    const validateEnglishItem4 = (rule, value, callback) => {
      if (/[\u4e00-\u9fa5]/.test(value)) {
        callback(
          new Error("English version cannot contain Chinese characters!")
        );
      } else {
        callback();
      }
    };
    const validateEnglishAnswer = (rule, value, callback) => {
      if (value.length > 0) {
        if (
          Array.isArray(value) &&
          value.some((item) => /[\u4e00-\u9fa5]/.test(item))
        ) {
          callback(
            new Error("English version cannot contain Chinese characters!")
          );
        } else {
          callback();
        }
      } else {
        callback(new Error("Answer cannot be empty!"));
      }
    };
    const validateEnglishRemark = (rule, value, callback) => {
      if (/[\u4e00-\u9fa5]/.test(value)) {
        callback(
          new Error("English version cannot contain Chinese characters!")
        );
      } else {
        callback();
      }
    };
    //这里存放数据
    return {
      showQuestionTranslated: false,
      questionTranslated: {
        id: "",
        question: "",
        item1: "",
        item2: "",
        item3: "",
        item4: "",
        answer: "",
        remark: "",
        questionId: "",
      },
      specialCaresList: [],
      editFlag: true, //表示提交操作是更新还是添加,true表示更新,false表示添加
      tableForm: {
        question: "",
        subjectId: "",
        item1: "",
        item2: "",
        item3: "",
        item4: "",
        answer: "",
        remark: "",
        specialCareId: null,
      },
      showSpecialList: false,
      answer: ["A", "B", "C", "D"],
      subjects: [],
      subjectTree: [], // 存储树形结构数据
      selectedSubjectPath: [], // 存储级联选择器选中的路径
      tableRules: {
        question: [
          {
            require: true,
            trigger: "blur",
            validator: validateQuestion,
          },
        ],
        subjectId: [
          {
            require: true,
            trigger: "blur",
            validator: validateSubject,
          },
        ],
        item1: [{ required: true, trigger: "blur", validator: validateItem1 }],
        item2: [{ required: true, trigger: "blur", validator: validateItem2 }],
        item3: [{ required: true, trigger: "blur", validator: validateItem3 }],
        item4: [{ required: false, trigger: "blur", validator: validateItem4 }],
        answer: [{ require: true, validator: validateAnswer, trigger: "blur" }],
        remark: [{ require: false }],
      },
      questionTranslatedRules: {
        question: [
          {
            require: true,
            trigger: "blur",
            validator: validateEnglishQuestion,
          },
        ],
        item1: [
          { required: true, trigger: "blur", validator: validateEnglishItem1 },
        ],
        item2: [
          { required: true, trigger: "blur", validator: validateEnglishItem2 },
        ],
        item3: [
          { required: true, trigger: "blur", validator: validateEnglishItem3 },
        ],
        item4: [
          { required: false, trigger: "blur", validator: validateEnglishItem4 },
        ],
        answer: [
          { require: true, validator: validateEnglishAnswer, trigger: "blur" },
        ],
        remark: [
          { require: false, validator: validateEnglishRemark, trigger: "blur" },
        ],
      },
    };
  },
  props: {
    disabled: { type: Boolean, default: false },
    questionId: {
      type: Number,
      default: function () {
        return { type: 1 };
      },
    },
    dialogFormVisible: false,
  },
  //计算属性 类似于 data 概念
  computed: {
    visible: {
      get() {
        return this.dialogFormVisible;
      },
      set(value) {
        this.$emit("update:dialogFormVisible", {
          type: "detail",
          val: value,
        });
      },
    },
  },
  //监控 data 中的数据变化
  // watch: {
  //   tableForm: {
  //     handler(newVal, oldVal) {
  //       // 监听到 obj 发生变化时的处理逻辑
  //       this.chapters = [];
  //       if (newVal.subject) {
  //         subjectApi.getByName(newVal.subject).then((res) => {
  //           this.chapters = res.data;
  //         });
  //       }
  //     },
  //     deep: true, // 开启深度监视
  //   },
  // },
  //方法集合
  methods: {
    getQuestionTranslated: async function () {
      const res = await questionTranslatedApi.getByQuestionId(
        this.tableForm.id
      );

      if (res.data) {
        this.questionTranslated = res.data;
        let arr = res.data.answer.split("+");
        this.questionTranslated.answer = arr;
        this.showQuestionTranslated = true;
        //当题目有英文版的时候，在中文版的表单的右侧再显示一个英文版的表单
      } else {
        this.questionTranslated = null;
        this.showQuestionTranslated = false;
        this.$message.error("未找到双语版信息，请联系管理员添加。");
      }
    },
    checkQuestionTranslated: async function () {
      const res = await questionTranslatedApi.getByQuestionId(
        this.tableForm.id
      );
      if (res.data) {
        this.questionTranslated = res.data;
        let arr = res.data.answer.split("+");
        this.questionTranslated.answer = arr;
        this.showQuestionTranslated = true;
      } else {
        this.questionTranslated = null;
        this.showQuestionTranslated = false;
        this.$message.error("未找到双语版信息，请联系管理员添加。");
      }
    },
    handleSubjectChange(value) {
      // 当级联选择器值变化时，将最后一个值赋给 subjectId
      if (value && value.length > 0) {
        this.tableForm.subjectId = value[value.length - 1];
        this.getSpecialCares();
      } else {
        this.tableForm.subjectId = "";
      }
    },
    submit(tableForm) {
      // 验证中文表单
      this.$refs[tableForm].validate((valid) => {
        if (!valid) {
          console.log("中文表单验证失败!!");
          return false;
        }

        // 如果显示英文版表单，则也验证英文版表单
        if (this.showQuestionTranslated) {
          this.$refs.questionTranslated.validate((valid) => {
            if (!valid) {
              console.error("英文表单验证失败!!");
              return false;
            }

            // 中文和英文表单都验证通过，执行提交操作
            this.performSubmit();
          });
        } else {
          // 只验证了中文表单，执行提交操作
          this.performSubmit();
        }
      });
    },
    performSubmit: async function () {
      if (this.editFlag) {
        const res = await questionApi.update(this.tableForm);
        if (this.showQuestionTranslated) {
          const response = await questionTranslatedApi.edit(
            this.questionTranslated
          );
          this.$message({
            message: `${response.message}`,
            type: "success",
          });
        } else {
          this.$message({
            message: `${res.message}`,
            type: "success",
          });
        }
        this.$emit("update:dialogFormVisible", {
          type: "detail",
          val: false,
        });
      } else {
        const res = await questionApi.add(this.tableForm);
        this.$message({
          message: `${res.message}`,
          type: "success",
        });
        this.$emit("update:dialogFormVisible", {
          type: "detail",
          val: false,
        });
      }
    },
    resetHandler(tableForm) {
      this.$refs[tableForm].resetFields();
      this.selectedSubjectPath = [];
    },
    init: async function () {
      const res = await questionApi.getById(this.questionId);
      const {
        item1,
        item2,
        item3,
        item4,
        question,
        remark,
        subjectId,
        id,
        specialCareId,
      } = res.data;
      this.tableForm = {
        item1,
        item2,
        item3,
        item4,
        question,
        remark,
        subjectId,
        id,
        specialCareId,
      };
      let arr = res.data.answer.split("+");
      this.$set(this.tableForm, "answer", arr);
      this.getSubject().then(() => {
        // 获取科目后，找到对应的路径并设置
        this.findSubjectPath(this.subjectTree, subjectId);
      });
    },
    getSubject() {
      return subjectApi.getAllTree().then((res) => {
        // 处理树结构，移除空的 children 数组
        this.subjectTree = this.processTreeData(res.data);
        return this.subjectTree;
      });
    },
    // 处理树结构，移除空的 children 数组
    processTreeData(treeData) {
      return treeData.map((node) => {
        const processedNode = { ...node };

        // 如果 children 是空数组，则删除该属性
        if (processedNode.children && processedNode.children.length === 0) {
          delete processedNode.children;
        } else if (processedNode.children) {
          // 递归处理子节点
          processedNode.children = this.processTreeData(processedNode.children);
        }

        return processedNode;
      });
    },
    // 递归查找节点路径
    findSubjectPath(tree, targetId, currentPath = []) {
      for (const node of tree) {
        // 创建新路径，包含当前节点
        const path = [...currentPath, node.value];

        // 如果找到目标节点
        if (node.value === targetId) {
          this.selectedSubjectPath = path;
          return true;
        }

        // 如果有子节点，递归查找
        if (node.children && node.children.length > 0) {
          if (this.findSubjectPath(node.children, targetId, path)) {
            return true;
          }
        }
      }

      return false;
    },
    getSpecialCares() {
      specialCareApi.getBySubjectId(this.tableForm.subjectId).then((res) => {
        this.specialCaresList = res.data;
        this.showSpecialList = this.specialCaresList.length > 0;
        //this.specialCaresList 是一个数组，里面的对象有一个id和name，name用于下拉选择器显示，id用于数据绑定
      });
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {
    if (this.questionId != 0) {
      this.editFlag = true;
      this.init().then(() => {
        this.getSpecialCares();
      });
    } else {
      this.getSubject();
      this.editFlag = false;
      this.tableForm = {
        question: "",
        subjectId: "",
        specialCareId: null,
        item1: "",
        item2: "",
        item3: "",
        item4: "",
        answer: "",
        remark: "",
      };
    }
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>
<style scoped>
.form-container {
  display: flex;
  gap: 20px;
}

.form-item {
  flex: 1;
}
</style>
